<?php

/**
 * This is the model class for table "sd.goods_property".
 *
 * The followings are the available columns in table 'sd.goods_property':
 * @property string $id
 * @property string $goods_id
 * @property string $property_id
 *
 * The followings are the available model relations:
 * @property Goods $goods
 * @property Property $property
 */
class GoodsProperty extends CBaseActiveRecord
{
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'sd.goods_property';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('goods_id, property_id, value_id', 'required'),
			array('goods_id, property_id, value_id, stock_value_id', 'length', 'max'=>10),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id, goods_id, property_id, value_id, stock_value_id', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'goods' => array(self::BELONGS_TO, 'Goods', 'goods_id'),
			'property' => array(self::BELONGS_TO, 'Property', 'property_id'),
			'value' => array(self::BELONGS_TO, 'PropertyValue', 'value_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'goods_id' => 'Goods',
			'property_id' => 'Property',
			'value_id' => 'Value',
			'stock_value_id' => 'Stock Value',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id,true);
		$criteria->compare('goods_id',$this->goods_id,true);
		$criteria->compare('property_id',$this->property_id,true);
		$criteria->compare('value_id',$this->value_id,true);
		$criteria->compare('stock_value_id',$this->stock_value_id,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return GoodsProperty the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	public function saveByTarget($oTargetRow, $params, $property_size_id = array())
	{
		if(!$oTargetRow || $oTargetRow->id < 1)
			return false;

		$connection = $this->getDbConnection();
		$transaction = $connection->beginTransaction();
//print_r($property_size_id); exit;
		try
		{
			$this->deleteAllByAttributes(array('goods_id' => $oTargetRow->id));

			if($params && is_array($params))
			{
				foreach($params as $propertyId => $aValue)
				{
					foreach($aValue as $valueId => $val)
					{
						$oRow = new self;
						$aRow = array(
							'goods_id' => $oTargetRow->id,
							'property_id' => $propertyId,
							'value_id' => $valueId,
						);

						if(!empty($property_size_id[$valueId]))
						{
							$matches = array();
							if(preg_match('/(\d+)\[(\d+)\]/i', $property_size_id[$valueId], $matches))
							{
//								print_r($matches); exit;
								if(!empty($matches[1]) && !empty($matches[2]))
								{
									$aRow['stock_value_id'] = $matches[1];
									$aRow['count'] = $matches[2];
								}
							}
						}

						$oRow->setAttributes($aRow);
						$oRow->save();
					}
				}
			}

			$transaction->commit();
		}
		catch(CDbException $e)
		{
			$transaction->rollback();
		}

		return true;
	}

	public function getByType($id, $type = '3')
	{
		$aRes = Yii::app()->db->createCommand()
			->select('*')
			->from('property p')
			->join('goods_property gp', 'p.id = gp.property_id')
			->join('property_value pv', 'gp.value_id = pv.id')
			->group('gp.value_id')
			->where('gp.goods_id = :id AND p.type = :type', array(
			                                                   ':id' => $id,
			                                                   ':type' => $type
			                                              ))
			->queryAll();

		return $aRes;
		print_r($aRes); exit;

	}

	public function selectByRowset($oRowset, $type = '3')
	{
		if(!$oRowset)
			return $oRowset;

		$ids = array();
		foreach($oRowset as $oRow)
			$ids[$oRow->id] = $oRow->id;
//		print_r($ids); exit;
		if(!$ids)
			return $oRowset;

		$aRes = Yii::app()->db->createCommand()
			->select('*')
			->from('property_value pv')
			->join('goods_property gp', 'pv.id = gp.value_id')
			->join('property p', 'p.id = pv.property_id')
//			->group('gp.goods_id')
			->group('gp.value_id, gp.goods_id')
			->where('gp.goods_id IN('. implode(', ', $ids) .') AND p.type = :type', array(
			                                                   ':type' => $type
			                                              ))
			->queryAll();

		$aResIdKey = array();
		foreach($aRes as $aRow)
		{
			$aResIdKey[$aRow['goods_id']][] = $aRow;
		}

		foreach($oRowset as $key => $oRow)
		{
			if(!empty($aResIdKey[$oRow->id]))
				$oRowset[$key]->property[$type] = $aResIdKey[$oRow->id];
		}

//		print_r($aRes); exit;

		return $aRes;
		print_r($aRes); exit;

	}


	public function getListByStoreId(array $storeIds, $goodsId = null)
	{
		$oCriteria = $this->getDbCriteria();
		$oCriteria->addInCondition('stock_value_id', $storeIds);

		if($goodsId)
			$oCriteria->addInCondition('goods_id', (array)$goodsId);

		return $this->findAll($oCriteria);
	}


}
